<template>
  <div v-if="showModal" class="modal-overlay">
    <div class="modal-content">
      <h2>{{ modalTitle }}</h2>

      <!-- 单词输入 -->
      <div class="form-group">
        <label for="word">Word</label>
        <input type="text" v-model="wordData.word" id="word" placeholder="Enter word" />
      </div>

      <!-- 类别选择 -->
      <div class="form-group">
        <label for="category">Category</label>
        <select v-model="wordData.category" id="category">
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>

      <div class="modal-actions">
        <button @click="handleSave" class="btn-save">Save</button>
        <button @click="closeModal" class="btn-close">Close</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

// props 接收父组件传递的数据
const props = defineProps({
  showAddModal: {
    type: Boolean,
    required: true
  },
  showEditModal: {
    type: Boolean,
    required: true
  },
  currentWord: {
    type: Object,
    default: () => ({})
  },
  categories: {
    type: Array,
    required: true
  }
});

// 响应式数据
const wordData = ref({
  word: props.currentWord.word || '',
  category: props.currentWord.category || ''
});

// 计算属性
const showModal = computed(() => props.showAddModal || props.showEditModal);
const modalTitle = computed(() => (props.showAddModal ? 'Add Word' : 'Edit Word'));

// 监听 currentWord 的变化，更新 wordData
watch(() => props.currentWord, (newVal) => {
  wordData.value.word = newVal.word || '';
  wordData.value.category = newVal.category || '';
});

// 保存单词
const handleSave = () => {
  emit('save', wordData.value); // 触发父组件的 save 事件
  closeModal();
};

// 关闭模态框
const closeModal = () => {
  emit('close'); // 触发父组件的 close 事件
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input,
select {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-save,
.btn-close {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-close {
  background-color: #dc3545;
}

.btn-save:hover,
.btn-close:hover {
  opacity: 0.8;
}
</style>
